package dao;

import bean.Salary;
import util.JDBCutil;
import util.SQLUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by superzhaolu on 2017/6/26.
 */
public class SalaryDao {
    private Connection connection = JDBCutil.getConnection();

    public int addSalary(Salary salary) {
        int row = 0;
        String sql = "INSERT INTO salary(money) VALUES (?);";
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setInt(1, salary.getMoney());
            row = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }

    public List<Salary> SelectSalary() {
        List<Salary> list = new ArrayList<>();
        String sql = "SELECT * FROM salary";

        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Salary salary = new Salary();
                salary.setId(rs.getInt("id"));
                salary.setMoney(rs.getInt("money"));
                list.add(salary);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public Salary getSalary(int id) {
        Salary salary = new Salary();
        String sql = "SELECT * FROM salary WHERE id=?;";
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setInt(1, id);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                salary.setId(rs.getInt("id"));
                salary.setMoney(rs.getInt("money"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return salary;
    }

    public int deleteSalary(int id) {
        int row;
        String sql1 = "DELETE FROM people WHERE salary_id=?";
        SQLUtil.deleteInfo(sql1, id);
        PeopleDao peopleDao = new PeopleDao();
        peopleDao.deletePeople(id);
        String sql = "DELETE FROM salary WHERE id=?";
        row = SQLUtil.deleteInfo(sql, id);
        return row;
    }

    public int updateSalary(Salary salary) {
        int row = 0;
        String sql = "UPDATE salary SET money = ? WHERE id=? ;";
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setInt(1, salary.getMoney());
            ps.setInt(2, salary.getId());
            row = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return row;
    }
}
